<?php
/**
 * Created by PhpStorm.
 * User: liuqi.
 * Date: 2017/10/27 10:03.
 */

namespace home\Controller;


class PatientController extends ApibaseController
{
    function __construct()
    {
        parent::__construct();
    }

    /**
     * 患者列表
     */
    public function patient()
    {
        $page    = I('get.page', 1);
        $perpage = I('get.perpage', 10);
        $url     = [];
        $model   = M('PatientInfo')->where(['is_blacklist'=>0,'hospital_id'=>session('loginUid'),'delete_at'=>0]);
        if (trim(I('get.name'))) {
            $model               = $model->where(" patient_name like '%" . I('get.name') . "%'");
            $url['name'] = I('get.name');
        }
        if (trim(I('get.phone'))) {
            $model         = $model->where(['mobile' => trim(I('get.phone'))]);
            $url['phone'] = I('get.phone');
        }
        if (trim(I('get.zyh'))) {
            $model         = $model->where(['hospital_num' => trim(I('get.zyh'))]);
            $url['zyh'] = I('get.zyh');
        }
        if (trim(I('get.mzh'))) {
            $model         = $model->where(['outpatient_num' => trim(I('get.mzh'))]);
            $url['mzh'] = I('get.mzh');
        }
        $copy = clone $model;
        $getData = $model->page($page, $perpage)->select();
        $this->assign('page', setPage($copy->count(), $perpage, $page, '?' . http_build_query($url)));
        $this->assign('getData', $getData);
        $this->display('user/patient_management');
    }

    /**
     * 黑名单列表
     */
    public function blacklist_management(){
        $page = I('get.page',1);
        $perpage = I('get.perpage',10);
        $url = [];
        $model = M('PatientInfo')->where(['is_blacklist'=>1,'hospital_id'=>session('loginUid'),'detele_at'=>0]);
        if(trim(I('get.name'))){
            $model = $model->where('patient_name LIKE "%' . I('get.name') . '%"');
            $url['name'] = trim(I('get.name'));
        }
        if(trim(I('get.phone'))){
            $model = $model->where(['mobile'=>trim(I('get.phone'))]);
            $url['phone'] = trim(I('get.phone'));
        }
        $copy = clone $model;
        $getData = $model->page($page,$perpage)->field(['patient_id','patient_name','sex','age','head_img','add_at','warning_level','mobile'])->select();
        $this->assign('page', setPage($copy->count(), $perpage, $page, '?' . http_build_query($url)));
        $this->assign('getData',$getData);
        $this->display('patient/blacklist_management');
    }


    /**
     * 黑名单权限管理
     * @date:11-14
     * @editor:zyy
     */
    public function limits_management(){
        $page = I('get.page') ?: 1;
        $perpage = 20;
        $BlackPer_model = M('BlacklistPermission')->where(['hospital_id'=>session('loginUid')]);
        $url = $output = $outtype = array();
        if(I('get.uname')){
            $BlackPer_model = $BlackPer_model->where('uname LIKE "%'.I('get.uname').'%"');
            $url['uname'] = I('get.uname');
        }
        $dep = M('Department')->field('id,de_name')->select();
        foreach($dep as $k1=>$v1){
            $depArr[$v1['id']] = $v1['de_name'];
        }
        $data = $BlackPer_model->page($page, $perpage)->select();
        foreach($data as $k=>$v){
            $data[$k]['department_name'] = $depArr[$v['depart_id']];
        }
        $this->assign('PermissionData',$data);
        $this->assign('page', setPage($BlackPer_model->count(), $perpage, $page, '?' . http_build_query($url)));
        $this->display('patient/limits_management');
    }

    /**
     * 添加黑名单权限
     * create by: liuqi
     * Date:2018-1-18 16:36:36
     */

    public function addBlackManage()
    {
        if(IS_POST){
            if (I('post.postData')) {
                parse_str(htmlspecialchars_decode(I('post.postData')), $postData);
            }

            if($postData['admin'] && $postData['name']){
                $user_id = M('UserInfo')->where(['user_name'=>trim($postData['name']),'depart_id'=>$postData['admin']])->getField('user_id');
                if($user_id){
                    $exists = M('BlacklistPermission')->where(['uname'=>$postData['name']])->find();
                    if($exists){
                        dataFormat('',1,'用户已添加');
                    }
                    $data = [
                        'user_id'=>$user_id,
                        'hospital_id'=>session('loginUid'),
                        'uname'=>$postData['name'],
                        'department'=>$postData['admin'],
                        'is_pass'=>1,
                        'add_at'=>time(),
                        'update_at'=>time()
                    ];
                    $res = M('BlacklistPermission')->add($data);
                    if($res){
                        dataFormat('',0,'添加成功');
                    }else{
                        dataFormat('',3,'添加失败');
                    }
                }else{
                    dataFormat('',2,'添加失败,请查看用户是否是课室成员');
                }
            }
        }
    }

    /**
     * 获取科室
     * create by: liuqi
     * Date:2018-1-18 16:39:02
     */
    public function getDepartList()
    {
        $data = M('Department')->where(['status'=>1,'hospital_id'=>session('loginUid')])->field('id,de_name')->select();
        dataFormat($data,0,'success');
    }

    /*
     * 要添加的黑名单患者搜索接口
     * @date 2017-11-30
     * @param 搜索内容 string
     */
    public function search_user(){
        $str = I('post.str');
        $userData = M('PatientInfo')->where(['patient_name'=>['like','%'.$str.'%'],'is_blacklist'=>0,'hospital_id'=>session('loginUid')])->field('patient_id,patient_name,head_img')->select();
        if($userData){
            dataFormat($userData, 0, 'success');
        }else{
            $this->ajaxReturn(['code'=>1,'msg'=>'error']);
        }
    }

    /*
     * 加入黑名单接口
     */
    public function add_blacklist(){
        if(IS_POST){
            if (I('post.postData')) {
                parse_str(htmlspecialchars_decode(I('post.postData')), $postData);
            }
            if($postData['patient_name'] && $postData['phone_num']) {
                $patient_info = M('PatientInfo')->where(['patient_name'=>$postData['patient_name'],'mobile'=>$postData['phone_num'],'hospital_id'=>session('loginUid'),'delete_at'=>0])->find();
                if(!$patient_info){
                    dataFormat('', 3, '用户不存在');

                }
                if($patient_info['is_blacklist'] == 1){
                    dataFormat('', 2, '已经是黑名单成员');
                }
                switch ($postData['warn_level']) {
                    case '一级':
                        $warn_level = 1;
                        break;
                    case '二级':
                        $warn_level = 2;
                        break;
                    case '三级':
                        $warn_level = 3;
                        break;
                    case '四级':
                        $warn_level = 4;
                        break;
                    default:
                        $warn_level = 0;
                        break;
                }
                $head_img = '';
                if ($postData['user_img']) {
                    $head_img = uploadQiniu($postData['user_img'], 'patient_head_img');
                }
                $update = M('PatientInfo')->where(['patient_id' => $patient_info['patient_id'],'hospital_id'=>session('loginUid')])->setField(['is_blacklist' => 1, 'warning_level' => $warn_level, 'head_img' => $head_img, 'update_at' => time()]);
                if ($update) {
                    dataFormat('', 0, '添加成功');
                } else {
                    dataFormat('', 1, '添加失败');
                }
            }
        }
    }

    /*
     * 取消患者的黑名单设置
     * @date 2017-11-30
     * @param 患者id
     */
    public function del_blacklist()
    {
        if(I('get.patient_id')){
            $res = M('PatientInfo')->where(['patient_id'=>I('get.patient_id'),'hospital_id'=>session('loginUid')])->setField(['is_blacklist'=>0,'update_at'=>time()]);
            if($res){
                $this->showtips('删除成功');
            }else{
                $this->showtips('删除失败');
            }
        }else{
            $this->showtips('参数有误');
        }

    }

    /**
     * 禁用/启用 黑名单权限
     * create by: liuqi
     * Date:2018-1-19 10:05:03
     */
    public function setBlackManageStu()
    {
        if(I('post.id') && in_array(I('post.status'),[0,1])) {
            $is_pass = intval(I('post.status'));
            $set = M('BlacklistPermission')->where(['id' => intval(I('post.id')), 'hospital_id'=>session('loginUid'),'is_pass' => $is_pass])->setField(['is_pass' => !$is_pass, 'update_at' => time()]);
            if ($set) {
                dataFormat('', 0, '设置成功');
            }
            dataFormat('', 2, '设置失败');
        }else{
            dataFormat('', 1, '参数有误');
        }
    }

    /**
     * 患者绑定腕带
     */
    public function bindWristband()
    {
        if (IS_POST) {
            if (I('post.postData')) {
                parse_str(htmlspecialchars_decode(I('post.postData')), $postData);
            }
            if ($postData['wristlet_num'] && $postData['edition_num'] && $postData['name'] && $postData['phone_num']) {
                $Wristband = M('Wristband');
                $patientModel = M('PatientInfo');
                $Wristband->startTrans();
                $have_patient = $patientModel->where(['patient_name'=>$postData['name'],'mobile'=>$postData['phone_num'],'hospital_id'=>session('loginUid')])->field('patient_id')->find();
                if(!$have_patient){
                    dataFormat('', 4, '该患者不存在');
                }
                $is_bind = $Wristband->where(['unbind_at' => 0, 'hospital_id'=>session('loginUid'),'patient_id' => $have_patient['patient_id'], 'status' => 1])->find();
                $is_wrist_bind = $Wristband->where(['wristband_num'=>$postData['wristlet_num'],'status'=>1])->find();
                if($is_wrist_bind){
                    dataFormat('', 5, '设备已经绑定');
                }
                if ($is_bind) {
                    dataFormat('', 1, '患者已经绑定');
                }

                $qr_url = '';
                if($postData['QR_code']){
                    $qr_url = uploadQiniu($postData['QR_code'], 'qr');
                }
                $data = [
                    'wristband_num'  => $postData['wristlet_num'],
                    'hospital_id'    => session('loginUid'),
                    'patient_id'     => $have_patient['patient_id'],
                    'version'        => $postData['edition_num'],
                    'patient_name'   => $postData['name'],
                    'mobile'         => $postData['phone_num'],
//                    'hospital_num'   => I('post.hospital_num'),
//                    'outpatient_num' => I('post.outpatient_num'),
                    'qr_url'         => $qr_url,
                    'status'         => 1,
                    'bind_at'        => time()
                ];
                if ($Wristband->add($data)) {
                    $bind = $patientModel->where(['patient_id' => $have_patient['patient_id']])->setField(['is_bind_wristband' => 1]);
                    if ($bind) {
                        $Wristband->commit();
                        $patientModel->commit();
                        dataFormat('', 0, '绑定成功');
                    } else {
                        $Wristband->rollback();
                        $patientModel->rollback();
                        dataFormat('', 2, '绑定失败');
                    }
                } else {
                    dataFormat('', 3, '绑定失败');
                }
            }
        }else{
            dataFormat('', 6, '非法请求');
        }
    }


    /**
     * 患者腕带修改
     */
    public function editBindWristband()
    {
        if (I('post.dosubmit')) {
            $patient_id = I('post.patient_id');
            $qr_url = I('post.qr_url');
            $data = [
                'wristband_num'  => I('post.wristband_num'),
                'patient_id'     => $patient_id,
                'version'        => I('post.version'),
                'patient_name'   => I('post.patient_name'),
                'mobile'         => I('post.mobile'),
                'hospital_num'   => I('post.hospital_num'),
                'outpatient_num' => I('post.outpatient_num'),
                'qr_url'         => $qr_url{0}=='/'?uploadQiniu(UPLOAD_PATH . $qr_url, 'qr'):$qr_url,
            ];
            $update = M('Wristband')->where(['patient_id'=>$patient_id,'status'=>1])->setField($data);
            if ($update) {
                $this->showtips('修改成功');
            } else {
                $this->showtips('修改失败');
            }
        }
        if(I('get.patient_id')){
            $data = M('Wristband')->where(['patient_id'=>I('get.patient_id')])->find();
            $this->assign('getData',$data);
        }
        $this->assign('patient_id',I('get.patient_id'));
        $this->display('patient/editbindwristband');
    }

    /**
     * 解绑腕带
     */

    public function unBindWristband()
    {
        $patient_id = I('get.patient_id');
        if ($patient_id) {
            $is_bind = M('Wristband')->where(['unbind_at' => 0, 'patient_id' => $patient_id, 'status' => 1])->find();
            if (!$is_bind) {
                $this->showtips('该患者未绑定腕带');
                exit;
            }
            $save = [
                'unbind_at' => time(),
                'status'    => 0
            ];
            $Wristband = M('Wristband');
            $patientModel = M('PatientInfo');
            $Wristband->startTrans();
            $res  = $Wristband->where(['status' => 1, 'patient_id' => $patient_id, 'unbind_at' => 0])->setField($save);
            if ($res) {
                $update = $patientModel->where(['patient_id'=>$patient_id])->setField(['is_bind_wristband'=>0]);
                if($update){
                    $Wristband->commit();
                    $patientModel->commit();
                    $this->showtips('解绑成功');
                }else{
                    $Wristband->rollback();
                    $this->showtips('解绑失败');
                }
            } else {
                $this->showtips('解绑失败');
            }
        }
    }

    /**
     * 后台添加患者信息
     */
    public function addPatient()
    {
        if(IS_POST){
            if (I('post.postData')) {
                parse_str(htmlspecialchars_decode(I('post.postData')), $postData);
            }


            if($postData['patient_name'] && $postData['age'] && $postData['mobile'] && $postData['password'] && in_array($postData['sex'],[0,1])) {
                $exists = M('PatientInfo')->where(['mobile'=>trim($postData['mobile']),'delete_at'=>0])->find();
                if($exists){
                    dataFormat('',3,'添加失败,手机号已存在');
                }
                $data['patient_code'] = '';//医院唯一编码
                $randStr = randstr(5);
                $password = md5(trim($postData['password']) . $randStr);
                $data = [
                    'hospital_id'       => session('loginUid'),
                    'patient_name'      => trim($postData['patient_name']),
                    'sex'               => trim($postData['sex']),
                    'age'               => trim($postData['age']),
                    'mobile'            => trim($postData['mobile']),
                    'hospital_num'      => trim($postData['hospital_num']),
                    'outpatient_num'    => trim($postData['putpatient_num']),
                    'is_bind_wristband' => 0,
                    'wechat'            => trim($postData['wechat']),
                    'salt'              => $randStr,
                    'password'          => $password,
                    'add_at'            => time(),
                    'update_at'         => time()
                ];

                if (M('PatientInfo')->add($data)) {
                    dataFormat('',0,'添加成功');
                } else {
                    dataFormat('',1,'添加失败');
                }
            }
        }
    }

    /**
     * 后台修改患者信息
     */
    public function editPatient()
    {
        if(I('post.dosubmit')){
            if(I('post.patient_id')){
                $data                 = [
                    'patient_name'      => trim(I('post.patient_name')),
                    'sex'               => I('post.sex'),
                    'age'               => I('post.age'),
                    'mobile'            => I('post.mobile'),
                    'hospital_num'      => I('post.hospital_num'),
                    'outpatient_num'    => I('outpatient_num'),
                    'wechat'            => I('post.wechat'),
                    'update_at'         => time()
                ];
                $update = M('PatientInfo')->where(['patient_id'=>I('post.patient_id')])->setField($data);
                if($update){
                    $this->showtips('修改成功');
                }else{
                    $this->showtips('修改失败');
                }
            }
        }
        if(I('get.patient_id')){
            $data = M('PatientInfo')->where(['patient_id'=>I('get.patient_id')])->find();
            $this->assign('patient_id',I('get.patient_id'));
            $this->assign('getData',$data);
            $this->display('patient/edit_patient');
        }
    }

    /**
     * 删除患者
     */
    public function delPatient()
    {
        if(I('post.patient_id')){
            $del = M('PatientInfo')->where(['patient_id'=>I('post.patient_id')])->setField(['update_at'=>time(),'delete_at'=>time()]);
            if($del){
                dataFormat('',0,'删除成功');
            }else{
                dataFormat('',1,'删除失败');
            }
        }
    }

    /**
     * 腕带管理
     * create by: liuqi
     * Date:2018-1-18 14:43:24
     */
    public function wristlet_management(){
        $page = I('get.page',1);
        $perpage = I('get.perpage',10);
        $url = [];
        $list = M('Wristband w')->join('hos_patient_info h ON w.patient_id = h.patient_id','LEFT')->field('w.*,h.hospital_num,h.outpatient_num')->where(['w.status'=>1,'w.hospital_id'=>session('loginUid')]);

        if(trim(I('get.wristlet_num'))){
            $list = $list->where(['wristband_num'=>trim(I('get.wristlet_num'))]);
            $url['wristband_num'] = trim(I('get.wristlet_num'));
        }
        if(trim(I('get.name'))){
            $list = $list->where(['patient_name'=>trim(I('get.name'))]);
            $url['name'] = trim(I('get.name'));
        }
        $copy = clone $list;
        $getData = $list->page($page, $perpage)->select();
        $this->assign('page', setPage($copy->count(), $perpage, $page, '?' . http_build_query($url)));
        $this->assign('getData', $getData);
        $this->display('patient/wristlet_management');
    }


    public function upFile()
    {
        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize   =     0 ;// 设置附件上传大小
        $upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
        $upload->rootPath  =     $_SERVER['DOCUMENT_ROOT'] . '/../../statics/upload/image/'; // 设置附件上传根目录
        $upload->savePath  =     ''; // 设置附件上传（子）目录
        // 上传文件
        $info   =   $upload->upload();
        if(!$info) {// 上传错误提示错误信息
            exit(json_encode(['code'=>1,'msg'=>'上传失败']));
        }else{
            exit(json_encode(['code'=>0,'msg'=>'../../statics/upload/image/'.$info['file']['savepath'].$info['file']['savename']]));
        }
    }



}